package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApAuthor;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.feign.article.ArticleFeign;
import com.heima.feign.media.MediaFeign;
import com.heima.media.entity.WmUser;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.io.filefilter.MagicNumberFileFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-06-30
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    private MediaFeign mediaFeign;


    @Autowired
    private ArticleFeign articleFeign;


    @Autowired
    private IApUserService apUserService;


    /**
     * 根据查询条件实名认证状态分页查询列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listByStatus(AuthDto dto) {
        //1.构建分页对象
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());

        //2.构建查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        //3.执行分页查询
        page = this.page(page, queryWrapper);

        //4.封装响应结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }


    /**
     * 管理员进行实名审核操作
     *
     * @param dto  入参
     * @param type 0：审核失败   1：审核通过
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult auth(AuthDto dto, int type) {
        //1.根据入参中实名认证记录ID查询实名认证记录 修改实名认证表状态
        ApUserRealname userRealname = this.getById(dto.getId());
        //1.1 根据参数中type 审核结果类型
        if (type == UserEnum.USER_REALNAME_OP_FAIL.getVal()) {
            //更新驳回原因
            userRealname.setStatus(UserEnum.USER_REALNAME_STATUS_FAIL.getVal());
            userRealname.setReason(dto.getReason());
            this.updateById(userRealname);
            return ResponseResult.okResult("审核已被驳回");
        }
        //1.2 管理员进行审核通过
        userRealname.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        this.updateById(userRealname);


        //2.远程调用自媒体微服务：新增自媒体用户
        //2.1 根据APP用户ID查询APP用户信息-为了封装自媒体用户对象
        ApUser apUser = apUserService.getById(userRealname.getUserId());

        //2.2 基于得到APP用户对象，封装自媒体用户对象，完成远程调用
        if (apUser != null) {
            WmUser wmUser = createWmuser(apUser);

            //3.远程调用作者微服务：新增作者用户；更新自媒体用户作者外键；更新APP用户标记，认证状态
            if (wmUser != null) {
                ApAuthor apAuthor = createAuthor(apUser, wmUser);
                if (apAuthor != null) {
                    //3.1 更新自媒体用户作者外键
                    wmUser.setApAuthorId(apAuthor.getId());
                    mediaFeign.updateWmUser(wmUser);

                    //3.2 更新APP用户标记，认证状态
                    apUser.setIsIdentityAuthentication(true);
                    apUser.setIsCertification(true);
                    apUser.setFlag(UserEnum.APPUSER_TYPE_WEMEDIA.getVal());
                    apUserService.updateById(apUser);
                    //todo 模拟发生异常
                    int i = 1/0;
                    return ResponseResult.okResult();
                }
            }
        }
        throw new RuntimeException("审核操作异常！");
    }


    /**
     * 构建媒体用户对象，完成新增自媒体用户远程调用
     *
     * @param apUser APP用户
     * @return
     */
    private WmUser createWmuser(ApUser apUser) {
        //1.构建自媒体用户对象
        WmUser wmUser = new WmUser();
        //1.1拷贝基本属性
        BeanUtils.copyProperties(apUser, wmUser);

        //1.2 设置其他属性
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        wmUser.setType(0);
        //TODO 作者逻辑外键为空 后续新增作者成功后 更新该字段值

        //2.完成新增自媒体用户远程调用
        ResponseResult<WmUser> result = mediaFeign.saveWmUser(wmUser);
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser data = result.getData();
            return data;
        }
        return null;
    }

    /**
     * 构建作者用户对象，完成新增作者，远程调用文章微服务
     *
     * @param apUser APP用户
     * @param wmUser 自媒体用户
     * @return
     */
    private ApAuthor createAuthor(ApUser apUser, WmUser wmUser) {
        //1.构建作者对象
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(UserEnum.AUTHOR_TYPE_WEMEDIA.getVal());
        apAuthor.setUserId(apUser.getId());
        apAuthor.setWmUserId(wmUser.getId());


        //2.远程调用文章微服务新增作者
        ResponseResult<ApAuthor> result = articleFeign.saveApAuthor(apAuthor);
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor data = result.getData();
            return data;
        }
        return null;
    }

}
